<template>
  <div id="app">
    <div class="app-container">
      <!-- 筛选区域 -->
      <div class="filter-container">
        <el-form :model="state.queryData" class="filter-form">
          <el-row :gutter="10" >
            <el-col :span="6">
              <el-form-item label="名称">
                <el-input v-model.trim="state.queryData.CustName" placeholder="请输入名称" size="small" clearable />
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item label="编码">
                <el-input v-model.trim="state.queryData.CustCode" placeholder="请输入编码" size="small" clearable />
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <div class="filter-actions">
                <el-button type="primary" @click="conditionEnter">查询</el-button>
                <el-button type="danger" @click="resetQuery">重置</el-button>
                <el-button type="primary" @click="handleAdd">新增客户</el-button>
              </div>
            </el-col>
          </el-row>

        </el-form>


      </div>

      <!-- 表格工具栏 -->
      <div class="table-container">
        <!-- 表格区域 -->
        <div class="table-wrapper">
          <el-table
              v-loading="state.loading"
              :data="state.table.data"
              style="width: 100%"
              highlight-current-row
              max-height="700px"
              show-overflow-tooltip
              @current-change="selecUpdateChange"
              empty-text="暂无数据"
          >
            <el-table-column type="index" label="序号" width="60" align="center" fixed />

            <el-table-column label="客户编码" prop="CustCode" fixed/>

            <el-table-column prop="CustName" label="客户名称" />
            <el-table-column prop="Createby" label="创建人"  />

            <el-table-column prop="Createtime" label="创建时间">
              <template #default="{ row }">
                <div>{{ parseTime(row.Createtime, '{y}-{m}-{d}') }}</div>
              </template>
            </el-table-column>
            <el-table-column prop="action" label="操作">
              <template #default="{ row }">
                <el-link :underline="false" @click="handleDelete(row.Id)" type="danger">删除</el-link>
              </template>
            </el-table-column>


          </el-table>
        </div>

        <!-- 分页控件 -->
        <div class="pagination-container">
          <el-pagination
              background
              layout="total, sizes, prev, pager, next, jumper"
              :total="state.table.total"
              :page-size="state.table.pageSize"
              :current-page="state.table.currentPage"
              :page-sizes="[10, 20, 50, 100]"
              @size-change="handleSizeChange"
              @current-change="pageChange"
          />
        </div>
      </div>
    </div>
  </div>

  <!-- 合同详情对话框 -->
  <el-dialog
      :title="state.title"
      v-model="state.dialogSelectEnt"
      width="60%"
      top="5vh"
      draggable
      :close-on-click-modal="false"
  >
    <div class="contract-info-section">
      <CumtorsList :UserCode="state.UserCode" @success="changeSuccess" ref="cumtorsRef"></CumtorsList>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closeDialog">取 消</el-button>
        <el-button type="primary" @click="submitForm" :loading="state.loading">确 定</el-button>
      </div>
    </template>
  </el-dialog>


</template>

<script setup lang="tsx">
import {computed, defineProps, reactive,defineEmits, ref, toRefs, watch} from "vue"
import {DeleteCumData, GetCumPageData,addUserToCust} from "@/api/base"
import {debounce, parseTime} from "@/utils/util";
import {cubasdocStore} from "@/stores/modules/cubasdoc";
import CumtorsList from './cumtors.vue'
const emit = defineEmits(['success']);


const tAdaptivePageRef: any = ref(null)

const cubasdoc = cubasdocStore()

const props = defineProps({
  UserCode: {
    type: String,
    default: null
  }
})

let {UserCode} = toRefs(props)


const handleDelete = async(row: any) => {
  ElMessageBox.confirm('确认删除分配？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    let axiosResponse = await DeleteCumData([row]);
    if (axiosResponse.Code==='OK'){
      ElNotification.success({
        title: '提示',
        message: '删除分配成功',
        offset: 200
      })
      await getData(1)
    }else {
      ElNotification.success({
        title: '提示',
        message: '删除分配失败：'+axiosResponse.Result,
        offset: 200
      })
    }
  })
}

//表格配置
const state: any = reactive({
  roleList: [],
  queryData: {
    CustCode:null,//客户编码
    CustName:null,//客户名称
  },
  UserCode:'',
  table: {
    total: 0,
    currentPage: 1,
    pageSize: 10,
    layout: "total,sizes, slot, prev, pager, next, jumper",
    prevText: "上一页",
    nextText: "下一页",
    // 接口返回数据
    data: [],
    firstColumn: { type: 'radio', fixed: true },
    // 表头数据
    columns: [
      { prop: 'index', label: '序号', minWidth: 55, slotName: 'index',fixed: 'left' },
      { prop: 'JobNum', label: '工作号', minWidth: 120,slotName: 'JobNum',fixed: 'left' },
      { prop: 'GDStatus', label: '归档状态', minWidth: 90,slotName:'GDStatus'},
      // { prop: 'ContractNum', label: '合同编码', minWidth: 120 },
      { prop: 'CustName', label: '客户名称', minWidth: 200 },
      // { prop: 'ContractName', label: '合同名称', minWidth: 120 },
      { prop: 'ProjectName', label: '项目名称', minWidth: 200 },
      { prop: 'ContractAmount', label: '合同总价(元)', minWidth: 110,slotName: 'ContractAmount' },
      { prop: 'DeliveryDate', label: '交付日期', minWidth: 110, slotName: 'DeliveryDate' },
      // { prop: 'DeliveryLocation', label: '交付地点', minWidth: 160 },
      // { prop: 'CustCode', label: '客户编码', minWidth: 120 },

      // { prop: 'CustAdd', label: '客户地址', minWidth: 200 },
      { prop: 'Type', label: '合同类型', minWidth: 100, slotName: 'Type' },
      { prop: 'IsMoudel', label: '合同模板', minWidth: 100, slotName: 'IsMoudel' },
      { prop: 'State', label: '状态', minWidth: 70, slotName: 'State' },
      { prop: 'IsSale', label: '销售订单', minWidth: 100, slotName: 'IsSale' },
      { prop: 'BGState', label: '变更状态', minWidth: 100, slotName: 'BGState' },

      // { prop: 'BankAccount', label: '银行账户', minWidth: 120 },
      // { prop: 'Tax', label: '税号', minWidth: 200 },
      // { prop: 'BankCode', label: '行号', minWidth: 160 },
      // { prop: 'SigningLocation', label: '签订地点', minWidth: 160 },
      { prop: 'versionNum', label: '版本', minWidth: 60 },

      { prop: 'DDate2', label: '单据日期', minWidth: 100, slotName: 'DDate' },
      { prop: 'createDate', label: '制单时间', minWidth: 145, slotName: 'CreateDate' },
      { prop: 'createBy', label: '建单人', minWidth: 80 },
    ]
  },
  loading:false,
  customersList:[],
  dialogSelectEnt:false,
  ids:[]
})



//选择项
const cusoptions = ref(cubasdoc.data)

// 最终参数获取
const getQueryData = computed(() => {
  const data = toRefs(state.queryData)
  let CustName = {name: "CustName", value: data.CustName?.value,wheretype:'1'}
  let CustCode = {name: "CustCode", value: data.CustCode?.value,wheretype:'1'}
  let UserCode = {name: "UserCode", value: state.UserCode,wheretype:'0'}
  //转换查询参数
  let where=[]
  console.log(state.UserCode,"state.UserCode")
  if(state.UserCode && state.UserCode !==''&& state.UserCode !==null){
    where.push(UserCode)
  }
  if(data.CustName?.value && data.CustName?.value !==''&& data.CustName?.value !==null){
    where.push(CustName)
  }
  if(data.CustCode?.value && data.CustCode?.value !=='' && data.CustCode?.value !==null){
    where.push(CustCode)
  }
  return {
    PageIndex: data.PageIndex?.value,
    PageSize : data.PageSize?.value,
    where
  }
})



//关闭弹窗
function closeDialog() {
  state.dialogSelectEnt = false
}

//关闭弹窗
function changeSuccess(e) {
  state.customersList = e
  console.log(state.customersList,"接收到数据")
}

// 点击查询按钮
const resetQuery = () => {
  state.queryData = {
    CustCode:null,//客户编码
    CustName:null,//客户名称
    UserCode:state.UserCode,
  }
  state.table.currentPage =1
  state.table.pageSize = 10
  console.log(state.queryData,state.UserCode,"1212")
  getData(1)
}

// 点击查询按钮
const conditionEnter = (data: any) => {
  state.table.currentPage =1
  state.table.pageSize = 10
  getData(1)
}

// 选择当前页码
const pageChange = val => {
  state.table.currentPage = val
  getData(val)
}

// 选择当前页码
const handleSizeChange = val => {
  state.table.pageSize = val;
  getData(val)
}


// 获取数据
const getData = async pageNum => {
  state.loading = true
  getQueryData.value.PageIndex = state.table.currentPage
  getQueryData.value.PageSize= state.table.pageSize
  // state.queryData.UserCode = state.UserCode
  console.log(state.UserCode,"UserCode1")
  let data=await GetCumPageData(getQueryData.value);
  if (data.Code==='OK'){
    state.table.data = data.Data
    state.table.total = data.Total
  }
  state.loading = false
}



//过滤单位
const cnvbasdocMethod = (query) => {
  if (query) {
    state.loading = true
    setTimeout(() => {
      state.loading = false

      cusoptions.value = cubasdoc.data.filter((its) => {
        return (its.cCusCode.toLowerCase().includes(query.toLowerCase()) || its.ccusabbname.toLowerCase().includes(query.toLowerCase()))
      })
    }, 200)
  } else {
    cusoptions.value = []
  }
}



//下拉表格选择数据
const selecUpdateChange = (e) => {
  state.selectedRow = e
}

// 提交表单

//获取条款内容
const submitForm = debounce(async () => {
  console.log(state.customersList.length,"121212")

  if (!state.customersList && state.customersList.length>0){
    ElNotification.warning({
      title: '提示',
      message: '请选择客户',
      offset: 200,
    })
    state.loading = false
    return
  }
  let res = await addUserToCust(state.customersList)
  if (res.Code == 'OK'){
    ElNotification.success({
      title: '提示',
      message: '保存成功',
      offset: 200,
    })
    closeDialog()
    await getData(1)
  }
  else {
    ElNotification.error({
      title: '提示',
      message: res.Result,
      offset: 200,
    })
  }
  state.loading = false
},false,1000)


// 监听debt-id变化自动刷新数据
watch(
    () => props.UserCode,
    (newVal, oldVal) => {
      if (newVal!=null && newVal!=''){
        state.UserCode = newVal
        console.log(state.UserCode,"UserCode")
        getData();
      }
    },
    { immediate: true } // 初始加载时执行一次
);

const cumtorsRef =ref(null)

const handleAdd = async() => {
  state.dialogSelectEnt =true
  setTimeout(()=>{
    cumtorsRef.value.getData()
  },500)
}


</script>

<style lang="scss" scoped>
.app-container {
  margin: 0 auto;
  background: white;
  border-radius: 10px;
  box-shadow: 0 2px 20px rgba(0, 0, 0, 0.08);
  overflow: hidden;
}

.header {
  padding: 20px 25px;
  background: linear-gradient(135deg, #409EFF 0%, #337ecc 100%);
  color: white;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.pagination-container{
  margin-top: 10px;
}
</style>
